﻿using System;
using System.IO;
using System.IO.Compression;
using Microsoft.Win32;

namespace WPFNote.Utilities.Common;

public class DataBaseHelper
{
    public string BackUp(out string destinationZipFile)
    {
        destinationZipFile = string.Empty;
        if (!File.Exists(AppSession.DbPath))
        {
            return "导出数据失败，数据库文件不存在！";
        }

        try
        {
            var databaseFolder = AppSession.DbBackUpPath;
            if (!Directory.Exists(databaseFolder))
            {
                Directory.CreateDirectory(databaseFolder);
            }

            var sourceFile = AppSession.DbPath;
            // 复制数据库文件到databaseFolder
            var databaseFile = Path.Combine(databaseFolder, Path.GetFileName(sourceFile));
            File.Copy(sourceFile, databaseFile, true);
            destinationZipFile = Path.Combine(databaseFolder, AppSession.ZipFileName);
            using (var fs = new FileStream(destinationZipFile, FileMode.Create))
            {
                using (var archive = new ZipArchive(fs, ZipArchiveMode.Create))
                {
                    // 创建ZIP存档中的条目，并将源文件添加到ZIP存档中
                    var entry = archive.CreateEntry(Path.GetFileName(databaseFile));
                    using (var entryStream = entry.Open())
                    {
                        using (var sourceFileStream = File.OpenRead(databaseFile))
                        {
                            sourceFileStream.CopyTo(entryStream);
                        }
                    }
                }
            }

            File.Delete(databaseFile);
            return !File.Exists(destinationZipFile) ? "导出数据失败" : string.Empty;
        }
        catch (Exception ex)
        {
            return $"备份数据失败，：{ex.Message}";
        }
    }

    public string Export()
    {
        try
        {
            var error = BackUp(out var destinationZipFile);
            if (!string.IsNullOrWhiteSpace(error))
            {
                return error;
            }

            // 设置保存文件对话框的初始目录为桌面
            var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            // 创建保存文件对话框实例
            var saveFileDialog = new SaveFileDialog
            {
                // 设置保存文件对话框的默认文件名和默认文件类型
                FileName = AppSession.ZipFileName,
                Filter = "压缩文件(*.zip)|*.zip",
                RestoreDirectory = true,
                InitialDirectory = desktopPath
            };
            // 显示保存文件对话框，并等待用户确认保存操作
            var result = saveFileDialog.ShowDialog();
            // 如果用户点击了保存按钮
            if (result == true)
            {
                // 获取用户选择的文件路径
                var filePath = saveFileDialog.FileName;
                File.Copy(destinationZipFile, filePath, true);
            }

            File.Delete(destinationZipFile);
            return string.Empty;
        }
        catch (Exception ex)
        {
            return $"导出数据失败，：{ex.Message}";
        }
    }

    public bool Import(string zipFile)
    {
        try
        {
            // 导入之前先备份
            BackUp(out _);

            var path = Path.Combine(AppSession.DbBackUpPath, AppSession.DbFileName);
            ZipFile.ExtractToDirectory(zipFile, AppSession.DbBackUpPath);
            if (!File.Exists(path))
            {
                return false;
            }

            File.Copy(path, AppSession.DbPath, true);
            return true;
        }
        catch
        {
            return false;
        }
    }
}